//
//  BBBook.swift
//  BBetter
//
//  Created by Gmc on 2020/3/1.
//  Copyright © 2020 Gmc. All rights reserved.
//

import UIKit

class BBBook: BBBaseViewController {
    private var data = [BBDataModel]()
    var selectedIndex: IndexPath?
    private var lock = false
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        self.loadCall = {
            if self.lock {
                return
            }
            self.lock = true
            self.loadData()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if let index = selectedIndex {
            let cell = tableView.cellForRow(at: index) as! BBDisplayCell
            cell.isSelected = false
        }
    }
    
    @objc  override func buttonAction(sender:UIBarButtonItem) {
        let window = UIApplication.shared.windows.first!
        let view:BBetterView = BBetterView(type: .book)
        view.show(view: window)
        view.callback = {[weak self] (para: [String: Any]) in
            Net.loadData(type: .post, para: para, url: "Book/Add") { (dict: [String: Any]) in
                let success:Bool = dict["success"] as! Bool
                if(success == false) {
                    let msgInfo = dict["msgInfo"] as! String
                    print(msgInfo)
                    return
                } else {
                    self?.data.removeAll()
                    for dict in dict["data"] as! [[String: Any]] {
                        let model = BBDataModel(dictionary: dict)
                        self?.data.append(model)
                    }
                    self?.tableView.reloadData()
                }
            }
        }
    }
    
    override func sendMessageToParent(obj: Any) {
        Net.loadData(type: .get, url: "Book") { (dict: [String: Any]) in
            let success:Bool = dict["success"] as! Bool
            if(success == false) {
                let msgInfo = dict["msgInfo"] as! String
                print(msgInfo)
                return
            } else {
                self.data.removeAll()
                for dict in dict["data"] as! [[String: Any]] {
                    let model = BBDataModel(dictionary: dict)
                    self.data.append(model)
                }
                self.tableView.reloadRows(at: [self.selectedIndex!], with: .automatic)
            }
        }
    }
    
    private func loadData() {
        Net.loadData(type: .get, url: "Book") { (dict: [String: Any]) in
            let success:Bool = dict["success"] as! Bool
            if(success == false) {
                let msgInfo = dict["msgInfo"] as! String
                print(msgInfo)
                self.lock = false
                return
            } else {
                self.data.removeAll()
                for dict in dict["data"] as! [[String: Any]] {
                    let model = BBDataModel(dictionary: dict)
                    self.data.append(model)
                }
                self.tableView.reloadData()
                self.lock = false
            }
        }
    }
}

extension BBBook {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! BBDisplayCell
        cell.model = data[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "删除") { (action: UIContextualAction, sourceView: UIView, completionHandler: @escaping (Bool) -> Void) in
            let model:BBDataModel = self.data[indexPath.row]
            self.data.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: .automatic);
            Net.loadData(type: .post, para: ["id": model.id], url: "Book/Delete") { (dict: [String : Any]) in
                let success = dict["success"] as! Bool
                if(success) {
                    var tempData:[BBDataModel] = [BBDataModel]()
                    for dict in dict["data"] as! [[String: Any]] {
                        let model = BBDataModel(dictionary: dict)
                        tempData.append(model)
                    }
                    if tempData.count != self.data.count {
                        self.data = tempData
                        self.tableView.reloadData()
                    }
                    for i in 0 ..< tempData.count {
                        let model:BBDataModel = self.data[i]
                        let tempM:BBDataModel = tempData[i]
                        if model.id != tempM.id {
                            self.data = tempData
                            self.tableView.reloadData()
                            break
                        }
                    }
                    completionHandler(true)
                } else {
                    /// toast error
                    completionHandler(false)
                }
            }
        }
//        let updateAction = UIContextualAction(style: .normal, title: "更新") { (action: UIContextualAction, sourceView: UIView, completionHandler: @escaping (Bool) -> Void) in
//            completionHandler(true)
//        }
//        updateAction.backgroundColor = UIColor.colorWithHexString(hexString: "00FF7F")
        let actions:[UIContextualAction] = [deleteAction]
        let action:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)
        action.performsFirstActionWithFullSwipe = true
        return action
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detail:BBDetail = BBDetail(type: .book)
        let model:BBDataModel = data[indexPath.row]
        detail.id = model.id
        navigationController?.pushViewController(detail, animated: true)
        selectedIndex = indexPath
    }
}
